#if PLAT_SOFT_TIMER_EN > 0 

#include "softtimer.h"

std::list<SoftTimer*> SoftTimer::m_timers;

SoftTimer::SoftTimer()
{
}

SoftTimer::SoftTimer(int interval, TimerType type)
{
    m_interval = interval;
    m_timerType = type;
}

SoftTimer::~SoftTimer()
{
    Stop();
}

void SoftTimer::SetInterval(int interval)
{
    m_interval = interval;
}

int SoftTimer::GetInterval()
{
    return m_interval;
}

void SoftTimer::SetTimerType(TimerType type)
{
    m_timerType = type;
}

SoftTimer::TimerType SoftTimer::GetTimerType()
{
    return m_timerType;
}

void SoftTimer::SetElapsed(std::function<void(SoftTimer &timer)> func)
{
    m_func = func;
}

void SoftTimer::Start()
{ 
    if(m_isRunning)
        return;

    m_currentMs = 0;
    m_isRunning = true;
    AddToTimerList(this);
}

void SoftTimer::Stop()
{
    if(!m_isRunning)
        return;

    m_isRunning = false;
    m_currentMs = 0;
    //不能在这里删除timer，导致for循环中删除it
    //下次更新自动删除
    // RemoveFromTimerList(this);
}

bool SoftTimer::IsRunning()
{
    return m_isRunning;
}

void SoftTimer::Run()
{
    //删除掉已经停止的定时器
    for(auto it = m_timers.begin(); it != m_timers.end();)
    {
        if(!(*it)->IsRunning())
        {
            it = m_timers.erase(it);
        }
        else 
        {
            it++;
        }
    }

    for(auto &t : m_timers)
    {
        t->Update();
        if(t->GetTimerType() == SoftTimer::TimerType::OneShot)
        {
            t->Stop();
        }
    }
}

void SoftTimer::AddToTimerList(SoftTimer *timer)
{
    m_timers.push_back(timer);
}

void SoftTimer::RemoveFromTimerList(SoftTimer *timer)
{
    m_timers.remove(timer);
}

void SoftTimer::Update()
{
    if(!m_isRunning)
        return;
    
    m_currentMs++;
    if(m_currentMs >= m_interval)
    {
        m_currentMs = 0;
        if(m_func)
        {
            m_func(*this);
        }
    }
}
#endif 
